package com.hp.authweb.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.hp.authweb.bean.Result;
import com.hp.authweb.model.MenuInfo;
import com.hp.authweb.model.RoleInfo;
import com.hp.authweb.repository.RoleRepository;

/**
 * @Description:角色服务类
 * @author hp
 * @date 2018年5月20日 上午9:15:59
 */
@Service
public class RoleService{

	@Autowired
	private RoleRepository roleRep;
	
	@Autowired
	private MenuService menuService;
	
	public RoleInfo findById(Long id) {
		RoleInfo role = roleRep.findById(id);
		if(!CollectionUtils.isEmpty(role.getMenuList())){
			List<MenuInfo> menuList = menuService.treeMenu(role.getMenuList());
			role.setMenuList(menuList);
		}
		return roleRep.findById(id);
	}
	
	/**
	 * 根据用户id获取用户拥有的角色信息
	 * @param id
	 * @return
	 */
	public List<RoleInfo> findByUserId(Long id) {
		
		return roleRep.findByUserId(id);
	}

	@Transactional
	public Result saveRole(Long id, String roleCode,String roleName, String perStr) {
		try {
			List<String> list = Arrays.asList(perStr.split(","));
			RoleInfo role = new RoleInfo();
			if(0!=id){
				role = roleRep.findOne(id);
			}
			role.setRoleCode(roleCode);
			role.setRoleName(roleName);
			List<MenuInfo> menuList = new ArrayList<>();
			list.forEach(action->{
				MenuInfo menu = new MenuInfo();
				menu.setId(Long.parseLong(action));
				menuList.add(menu);
			});
			role.setMenuList(menuList);
			roleRep.save(role);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
		return Result.success();
	}

	public List<RoleInfo> finaAllRole() {
		return roleRep.findAll();
	}
	
} 
